import { EnumCacheGroup } from "../../../common/enum/EnumCacheGroup";
import { EnumServiceType } from "../../../common/enum/EnumServiceType";
import { CS_DelCache, SC_DelCache } from "../../../common/protocols/Proto_DelCache";
import { CS_GetCache, SC_GetCache } from "../../../common/protocols/Proto_GetCache";
import { CS_SaveCache, SC_SaveCache } from "../../../common/protocols/Proto_SaveCache";
import { ComponentBasic } from "../../ecs/Component/ComponentBasic";
import { RPCComponent } from "./RPCComponent";



/**
 * 用于从cache server 增删查询数据
 *
 * @export
 * @class CacheComponent
 * @extends {ComponentBasic}
 */
export class CacheComponent extends ComponentBasic {

    public update(dt: number, servertime: number): void {
        
    }


    public do(): void {


    }





    public get(group: EnumCacheGroup, key: string): Promise<any> {

        const rpcComp: RPCComponent = <RPCComponent>this.entity.getComponent(RPCComponent);

        const cs: CS_GetCache = new CS_GetCache();
        cs.group = group;
        cs.key = key;


        return new Promise((resolve, reject) => {

            if(!rpcComp){
                resolve("");
            }
            rpcComp.callServiceByType(EnumServiceType.Cache, cs, (error: any, msg: SC_GetCache) => {

                if (error) {
                    resolve(null);
                    return;
                }
                

                resolve(msg.data);
                
                
            });
        });


    }


    public set(group: EnumCacheGroup, key: string,value:any,expiretime?:number): Promise<any> {

        return new Promise((resolve,reject)=>{
            const cs:CS_SaveCache = new CS_SaveCache();
            cs.group = group;
            cs.key = key;
            cs.value = value;
            cs.expiretime = expiretime;
            const rpcComp: RPCComponent = <RPCComponent>this.entity.getComponent(RPCComponent);

            if(!rpcComp){
                resolve(null);
            }
            rpcComp.callServiceByType(EnumServiceType.Cache, cs, (error: any, msg: SC_SaveCache) => {

                if (error) {
                    resolve(null);
                    return;
                }
                resolve(msg.value);
            });
        });
    }



    public del(group:EnumCacheGroup , key: string): Promise<any> {

        return new Promise((resolve,reject)=>{
            const cs:CS_DelCache = new CS_DelCache();
            cs.group = group;
            cs.key = key;

            const rpcComp: RPCComponent = <RPCComponent>this.entity.getComponent(RPCComponent);

            if(!rpcComp){
                resolve(null);
            }
            rpcComp.callServiceByType(EnumServiceType.Cache, cs, (error: any, msg: SC_DelCache) => {

                if (error) {
                    resolve(null);
                    return;
                }
                resolve(msg.errorcode);
            });
        });
    }

}   